package com.huaxin.hxmoduleworkorder.taskscheduler;

import com.huaxin.feignclient.system.SystemClient;
import com.huaxin.hxmoduleworkorder.mapper.ScheduledTaskConfigMapper;
import com.huaxin.hxmoduleworkorder.models.ScheduledTaskConfig;
import com.huaxin.hxmoduleworkorder.service.InspectionOrderService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Component
@Slf4j
public class DynamicTaskScheduler {

    private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private final TaskScheduler taskScheduler;
    private final ScheduledTaskConfigMapper taskConfigMapper;
    private final InspectionOrderService inspectionOrderService; // 你原来的业务服务
    private final SystemClient systemClient;

    public DynamicTaskScheduler(TaskScheduler taskScheduler,
                                ScheduledTaskConfigMapper taskConfigMapper,
                                InspectionOrderService inspectionOrderService,
                                SystemClient systemClient) {
        this.taskScheduler = taskScheduler;
        this.taskConfigMapper = taskConfigMapper;
        this.inspectionOrderService = inspectionOrderService;
        this.systemClient = systemClient;
    }

    /**
     * 系统启动时自动恢复启用的任务
     */
    @PostConstruct
    public void init() {
        log.info("Initializing dynamic scheduled tasks...");
        List<ScheduledTaskConfig> configs = taskConfigMapper.listAll();
        for (ScheduledTaskConfig config : configs) {
            if (!config.getIsEnabled()) {
                continue;
            }
            startTask(config.getTaskName(), config.getTemplateId(), config.getCronExpression());
            log.info("✅ 自动启动任务: {}", config.getTaskName());
        }
    }

    /**
     * 启动指定任务
     */
    public synchronized void startTask(String taskName) {
        ScheduledTaskConfig config = taskConfigMapper.getByTaskName(taskName);
        if (config == null) {
            throw new IllegalArgumentException("不支持的任务类型: " + taskName);
        }
        startTask(taskName, config.getTemplateId(), config.getCronExpression());
        // 更新数据库状态
        taskConfigMapper.updateEnabled(taskName, true);
    }

    private void startTask(String taskName, String templateId, String cronExpression) {
        if (scheduledTasks.containsKey(taskName)) {
            log.warn("任务 {} 已在运行", taskName);
            return;
        }

        Runnable task = () -> {
            log.info("🔧 执行动态任务: {} at {}", taskName, LocalDateTime.now());
            try {
                inspectionOrderService.createInspectionOrders(taskName, templateId); // 调用业务逻辑
            } catch (Exception e) {
                log.error("任务执行失败: " + taskName, e);
            }
        };

        ScheduledFuture<?> future = taskScheduler.schedule(task, new CronTrigger(cronExpression));
        scheduledTasks.put(taskName, future);
    }

    /**
     * 停止指定任务
     */
    public synchronized void stopTask(String taskName) {
        ScheduledFuture<?> future = scheduledTasks.remove(taskName);
        if (future != null) {
            future.cancel(false);
            taskConfigMapper.updateEnabled(taskName, false);
            log.info("🛑 已停止任务: {}", taskName);
        } else {
            log.warn("任务未运行: {}", taskName);
        }
    }

    /**
     * 获取当前运行中的任务名称列表
     */
    public List<String> getRunningTasks() {
        return new ArrayList<>(scheduledTasks.keySet());
    }

    /**
     * 获取所有支持的任务配置
     */
    public List<ScheduledTaskConfig> getAllTasks() {
        return taskConfigMapper.listAll();
    }
}
